﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Collections.ObjectModel;

namespace TGIApp.Service
{
    [AttributeUsage(AttributeTargets.Class)]
public class CustomErrorHandlerBehaviorAttribute : Attribute, IServiceBehavior, IErrorHandler
{
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
		protected Type ServiceType { get; set; }
		public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
		{
			//Dont do anything
		}
 
		public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection <ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
		{
			//dont do anything
		}
 
		public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
		{
			ServiceType = serviceDescription.ServiceType;
			foreach (ChannelDispatcher dispatcher in serviceHostBase.ChannelDispatchers)
			{
				dispatcher.ErrorHandlers.Add(this);
			}
		}
 
		public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
		{
			//fault = null; //Suppress any faults in contract
		}
 
		public bool HandleError(Exception error)
		{
            log.ErrorFormat("Service failed with message: {0}\n Inner Exception {1} \n Stack Trace: {2}", error.Message ,((error.InnerException!=null)?error.InnerException.Message:"No Inner Exception"), error.StackTrace.ToString() );
			return false;
		}
}
}